<template>
  <div class="task-hall-container">
    <!-- 接单大厅头部统计 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="8">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-content">
            <div class="stat-icon total-icon">
              <el-icon><DataBoard /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ unassignedTasks.length }}</div>
              <div class="stat-label">总计可接单</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-content">
            <div class="stat-icon high-icon">
              <el-icon><TopRight /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ highPriorityTasksCount }}</div>
              <div class="stat-label">高优先级</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-content">
            <div class="stat-icon completed-icon">
              <el-icon><Check /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ completedTodayCount }}</div>
              <div class="stat-label">今日已完成</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 任务列表 -->
    <el-card class="task-list-card" v-loading="loading">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <span class="task-title">可接单任务</span>
            <el-tag type="success" effect="dark" size="small">{{ unassignedTasks.length }}</el-tag>
          </div>
          <div class="header-filters">
            <el-select v-model="filterPriority" placeholder="优先级" size="small" style="width: 100px; margin-right: 10px;">
              <el-option label="全部优先级" value="" />
              <el-option label="高" value="高" />
              <el-option label="中" value="中" />
              <el-option label="低" value="低" />
            </el-select>
            <el-button type="primary" @click="fetchUnassignedTasks">查询</el-button>
          </div>
        </div>
      </template>
      
      <el-table :data="filteredUnassignedTasks" style="width: 100%" height="500px" size="default" :row-class-name="highlightPriority">
        <el-table-column prop="expected_service_date" label="预约日期" width="120" sortable>
          <template #default="scope">
            {{ scope.row.expected_service_date }}
          </template>
        </el-table-column>
        <el-table-column prop="expected_time_slot" label="时间段" width="100">
          <template #default="scope">
            {{ scope.row.expected_time_slot }}
          </template>
        </el-table-column>
        <el-table-column prop="type" label="任务类型" width="120">
          <template #default="scope">
            <el-tag type="success">保洁</el-tag>
          </template>
        </el-table-column>
        
        <!-- 共用字段 -->
        <el-table-column prop="contact_name" label="联系人" width="100">
          <template #default="scope">
            {{ scope.row.contact_name || '暂无信息' }}
          </template>
        </el-table-column>
        <el-table-column prop="contact_phone" label="联系电话" width="130">
          <template #default="scope">
            {{ scope.row.contact_phone || '暂无信息' }}
          </template>
        </el-table-column>
        
        <!-- 任务内容 - 特殊要求 -->
        <el-table-column label="特殊要求" width="180" show-overflow-tooltip>
          <template #default="scope">
            {{ scope.row.special_requirements || '标准保洁服务' }}
          </template>
        </el-table-column>
        
        <!-- 地址/位置 -->
        <el-table-column label="服务地址" width="260" show-overflow-tooltip>
          <template #default="scope">
            {{ scope.row.address || '未指定' }}
          </template>
        </el-table-column>
        
        <!-- 通用字段 -->
        <el-table-column prop="priority" label="优先级" width="100" align="center">
          <template #default="scope">
            <el-tag :type="getPriorityTag(scope.row.priority)" size="small">{{ scope.row.priority }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" align="center" fixed="right">
          <template #default="scope">
            <el-button size="small" type="success" @click="handleAccept(scope.row)">接单</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          :page-size="pageSize"
          :current-page="currentPage"
          @size-change="handleSizeChange"
          @current-page-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script>
import { ref, computed, onMounted, watch } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { 
  AlarmClock, 
  TopRight, 
  Check, 
  DataBoard 
} from '@element-plus/icons-vue';
import { dashboardService, cleaningService } from '@/api/tasks';

export default {
  name: 'CleaningTaskHall',
  components: {
    AlarmClock,
    TopRight,
    Check,
    DataBoard
  },
  setup() {
    const router = useRouter();
    const loading = ref(false);
    const unassignedTasks = ref([]);
    const total = ref(0);
    const currentPage = ref(1);
    const pageSize = ref(10);
    const filterPriority = ref('');
    const filterType = ref('cleaning'); // 固定为保洁类型
    const userRole = ref('');
    const completedTodayCount = ref(0);

    // 根据用户角色确定任务类型
    const initUserRoleAndTaskType = () => {
      // 从用户信息中获取角色
      const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
      userRole.value = userInfo.employeeType || '保洁工';
    };

    // 获取可接单任务
    const fetchUnassignedTasks = async () => {
      try {
        loading.value = true;
        const params = {
          page: currentPage.value,
          pageSize: pageSize.value,
          priority: filterPriority.value,
          type: 'cleaning' // 固定为保洁类型
        };
        
        const response = await dashboardService.getAvailableTasks(params);
        console.log('API完整响应:', response);
        
        const { data } = response;
        if (data.code === 200) {
          // 添加调试日志查看原始数据
          console.log('API返回原始数据:', data.data);
          
          // 过滤出保洁类型的任务
          unassignedTasks.value = data.data
            .filter(task => task.type === 'cleaning')
            .map(task => {
              // 使用后端返回的字段，确保与数据库表结构一致
              return {
                ...task,
                id: task.id,
                expected_service_date: task.expected_service_date || '未指定',
                expected_time_slot: task.expected_time_slot || '全天',
                special_requirements: task.special_requirements || '标准保洁服务',
                address: task.address || '未指定',
                contact_name: task.contact_name || '未指定',
                contact_phone: task.contact_phone || '未指定',
                priority: task.priority || '中',
                application_time: task.application_time || new Date().toISOString()
              };
            });
          console.log('处理后的任务数据:', unassignedTasks.value);
          total.value = data.total || unassignedTasks.value.length;
        } else {
          throw new Error(data.message || '获取数据失败');
        }
      } catch (error) {
        console.error('加载可接单任务失败:', error);
        console.error('错误详情:', error.response?.data || error.message);
        ElMessage.error(`加载可接单任务失败: ${error.response?.data?.message || error.message || '未知错误'}`);
      } finally {
        loading.value = false;
      }
    };

    // 获取今日已完成任务数量
    const fetchCompletedTodayCount = async () => {
      try {
        const { data } = await dashboardService.getPerformanceStats('today');
        if (data.code === 200) {
          completedTodayCount.value = data.data.completedOrders || 0;
        }
      } catch (error) {
        console.error('获取今日完成任务数量失败:', error);
        completedTodayCount.value = 0;
      }
    };

    // 统计数据计算
    const highPriorityTasksCount = computed(() => 
      unassignedTasks.value.filter(task => task.priority === '高').length
    );

    // 过滤未受理任务
    const filteredUnassignedTasks = computed(() => {
      let filtered = [...unassignedTasks.value];
      
      if (filterPriority.value) {
        filtered = filtered.filter(task => task.priority === filterPriority.value);
      }
      
      return filtered;
    });
    
    // 获取优先级标签类型
    const getPriorityTag = (priority) => {
      const map = {
        '高': 'danger',
        '中': 'warning',
        '低': 'info'
      };
      return map[priority] || '';
    };

    // 高亮优先级行
    const highlightPriority = (row) => {
      if (row.row.priority === '高') return 'high-priority-row';
      return '';
    };

    // 接单处理
    const handleAccept = async (task) => {
      try {
        loading.value = true;
        const response = await cleaningService.updateStatus(task.id, '已受理');
        
        if (response.data.code === 200) {
          ElMessage.success(`接单成功: 保洁任务 #${task.id}`);
          // 重新加载数据
          fetchUnassignedTasks();
        } else {
          throw new Error(response.data.message || '接单失败');
        }
      } catch (error) {
        console.error('接单失败:', error);
        ElMessage.error(`接单失败: ${error.message}`);
      } finally {
        loading.value = false;
      }
    };

    // 分页大小变化
    const handleSizeChange = (size) => {
      pageSize.value = size;
      fetchUnassignedTasks();
    };

    // 页码变化
    const handleCurrentChange = (page) => {
      currentPage.value = page;
      fetchUnassignedTasks();
    };
    
    // 初始化
    onMounted(() => {
      initUserRoleAndTaskType();
      fetchUnassignedTasks();
      fetchCompletedTodayCount();
    });

    return {
      loading,
      unassignedTasks,
      filteredUnassignedTasks,
      filterPriority,
      filterType,
      userRole,
      total,
      currentPage,
      pageSize,
      highPriorityTasksCount,
      completedTodayCount,
      fetchUnassignedTasks,
      getPriorityTag,
      highlightPriority,
      handleAccept,
      handleSizeChange,
      handleCurrentChange
    };
  }
};
</script>

<style scoped>
.task-hall-container {
  padding: 20px;
  background-color: #f0f2f5;
}

.stats-row {
  margin-bottom: 20px;
}

.stat-card {
  height: 100px;
  transition: all 0.3s;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 15px rgba(0,0,0,0.1);
}

.stat-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.stat-icon {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #fff;
  margin-right: 15px;
  font-size: 22px;
}

.high-icon {
  background-color: #E6A23C;
}

.total-icon {
  background-color: #67C23A;
}

.completed-icon {
  background-color: #409EFF;
}

.stat-info {
  display: flex;
  flex-direction: column;
}

.stat-value {
  font-size: 26px;
  font-weight: bold;
  color: #303133;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}

.task-list-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 10px;
}

.header-filters {
  display: flex;
  align-items: center;
}

.task-title {
  font-weight: 600;
  font-size: 16px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

/* 优先级高亮 */
.high-priority-row {
  background-color: #fff8f0;
}

:deep(.el-table__body tr.high-priority-row:hover > td) {
  background-color: #fff0d0 !important;
}
</style> 